package com.lagou.factory;

import com.lagou.utils.TransactionManager;

import java.lang.reflect.Proxy;

/**
 * @Author: Tengfei.Wang
 * @Description; 用于生产bean代理对象
 * @Date: 31/8/2020
 * @Modified by:
 */
public class ProxyFactory {

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

/*
    private ProxyFactory() {}

    private static ProxyFactory proxyFactory = new ProxyFactory();

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }
*/

    public Object getProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    Object invoke = null;
                    try {
                        //开启事务
                        transactionManager.beginTransaction();
                        invoke = method.invoke(o, args);
                        //关闭事务
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //回滚事务
                        transactionManager.rollback();
                    }
                    return invoke;
                });
    }
}
